package com.zlk.algorithm.dataStructure.array;

import com.sun.org.apache.bcel.internal.generic.PUSH;
import org.junit.Test;

import java.sql.Array;

/**
 * @program: algorithm
 * @ClassName Syclet2ArrayAndQuene
 * @description:用环形数组实现栈和队列
 * @author: slfang
 * @create: 2023-12-29 14:58
 * @Version 1.0
 **/
public class CircleArrayToStackAndQueue {


    @Test
    public void test(){
        CircleStack circleQueue = new CircleStack();
        for (int i = 0; i < 10; i++) {
            circleQueue.push(i);
        }
        System.out.println(circleQueue.poll());
        System.out.println(circleQueue.poll());
        System.out.println(circleQueue.poll());

        circleQueue.push(10);
        circleQueue.push(11);
        System.out.println(circleQueue.poll());
        System.out.println(circleQueue.poll());
    }



     class CircleQueue{
         public int beginIndex = 0;
         public int endIndex = 0;
         public int limit = 10;//限制数组的容量

         public int[] arr = new int[limit];

         public int size ;//目前已添加的长度

         void push(int val) {
             if(size==limit){
                 System.out.println("数组已满");
             }
             size++;
             arr[endIndex] = val;
             endIndex = nextIndex(endIndex);

         }

         /**
          * 不能只是简单++ 因为是循环数组，如果栈填出的话，前方数据会留位置
          */

         private int nextIndex(int i) {
             return i < limit - 1 ? i + 1 : 0;
         }

         int poll(){
             if(size==0){
                 return -1;
             }else{
                 int i = arr[beginIndex];
                 size--;
                 beginIndex = nextIndex(beginIndex);
                 return i;
             }
         }
     }



    class CircleStack {
        public int limit = 10;//限制数组的容量

        public int[] arr = new int[limit];

        public int size ;//目前已添加的长度

        void push(int val) {
            if(size==limit-1){
                System.out.println("数组已满");
            }
            arr[size++] = val;
        }



        int poll(){
            if(size==0){
                return -1;
            }else{
                return arr[--size];
            }
        }

    }





}
